//index.js
//获取应用实例
const app = getApp()
var utils = require('../../utils/util.js')
Page({
    data: {
        keyword:"",
        schoolid:"",
        isScholl:"",
        currentPage: 1,
		isreturn:false,
		curPage:1
    },
    onLoad: function(options) {
        var that=this;
		that.setData({
			q: options.q ? options.q : null
		})
		if (options.q!=undefined){
			let q = utils.getJson(decodeURIComponent(that.data.q));
			
			app.globalData.inv_id=q.inv_id;
			console.log(q);
		}
		
		this.setData({
			isScholl: wx.getStorageSync("schoolInfo")
		})
		if (app.globalData.key !== undefined) {
			this.getUserLocation();
			this.systemInfo();
			this.sliderList();
			this.articleList();
			this.goodsList(this.data.currentPage);
			this.schoolList(that.data.keyword);
		
		} else {
			//登录后获取店铺列表
				console.log("klsdfjklj")
			app.makeLogin((res) => {
				this.getUserLocation();
				this.systemInfo();
				this.sliderList();
				this.articleList();
				this.goodsList(this.data.currentPage);
				this.schoolList(that.data.keyword);

			});
		}



        
    },
    //定位方法
    getUserLocation: function() {
        var _this = this;
        wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
                    //未授权
                    wx.showModal({
                        title: '请求授权当前位置',
                        content: '需要获取您的地理位置，请确认授权',
                        success: function(res) {
                            if (res.cancel) {
                                //取消授权
                                wx.showToast({
                                    title: '拒绝授权',
                                    icon: 'none',
                                    duration: 1000
                                })
                            } else if (res.confirm) {
                                //确定授权，通过wx.openSetting发起授权请求
                                wx.openSetting({
                                    success: function(res) {
                                        if (res.authSetting["scope.userLocation"] == true) {
                                            wx.showToast({
                                                title: '授权成功',
                                                icon: 'success',
                                                duration: 1000
                                            })
                                            //再次授权，调用wx.getLocation的API
                                            _this.geo();
                                        } else {
                                            wx.showToast({
                                                title: '授权失败',
                                                icon: 'none',
                                                duration: 1000
                                            })
                                        }
                                    }
                                })
                            }
                        }
                    })
                } else if (res.authSetting['scope.userLocation'] == undefined) {
                    //用户首次进入页面,调用wx.getLocation的API
                    _this.geo();
                } else {
                    console.log('授权成功')
                    //调用wx.getLocation的API
                    _this.geo();
                }
            }
        })

    },
	//跳入推广二维码
	onCodeTap: function (res) {
		wx.navigateTo({
			url: '../code/code',
		})
	},
    // 获取定位城市
    geo: function() {
        var that = this;
        wx.getLocation({
            type: 'wgs84',
            success: function(res) {
                console.log(res);
                wx.setStorageSync("localhost", {
                    latitude: res.latitude,
                    longitude: res.longitude
                })
                that.storeList();
            }
        })
    },
	onStoreTap(){
		wx.navigateToMiniProgram({
			appId: 'wxce2b481e0e1c4ba8',
			path: 'pages/index/index',
			extraData: {
				foo: 'bar'
			},
			envVersion: 'trial',
			success(res) {
				// 打开成功
			}
		})
	},

    //输入学校关键词
    bindSchoolTap:function(e){
        console.log(e.detail.value);
        this.setData({
            curHdIndex:-1,
            schoolid:"",
			curPage: 1,
			school:[],
			keyword:e.detail.value
        })
		this.schoolList();
    },
    //tab学校ID切换
    tab: function (e) {
        var dataId = e.currentTarget.id;
        var schoolid = e.currentTarget.dataset.schoolid;
        var schooltitle = e.currentTarget.dataset.schooltitle;
        var curHdIndex = dataId;
        this.setData({
            curHdIndex: curHdIndex,
            schoolid: schoolid,
            schooltitle: schooltitle
        })
		
        wx.setStorageSync("schoolInfo", {
            schoolid:schoolid,
            schooltitle: schooltitle
        });
    },
    //显示学校弹窗
    onSchoolTap:function(e){
        this.setData({
            isScholl: ""
        })
    },
    //提交学校ID
    onSubmitTap:function(e){
        console.log(this.data.schoolid);
        if (this.data.schoolid==""){
            utils.showToast("请选择学校信息~")
            return false;
        }else{  
            this.setData({
                isScholl: wx.getStorageSync("schoolInfo"),
				goods:[],
				currentPage:1
            })
            this.storeList();

			this.goodsList(this.data.currentPage);
        }
    },
    //获取站点配置信息 
    systemInfo: function() {
        var that = this;
        utils.http("/api/v1/common/system", {}, function(res) {
            if (res.state == 1) {
                that.setData({
                    system: res.datas
                })
            } else {
                utils.message(res.datas)
            }
        })
    },
    //轮播图列表
    sliderList: function() {
        var that = this;
        utils.http("/api/v1/common/slider_list", {}, function(res) {
            if (res.state == 1) {
                that.setData({
                    slider: res.datas
                })
            } else {
                utils.message(res.datas)
            }
        })
    },
    //文章列表 （不分页）
    articleList: function() {
        var that = this;
        utils.http("/api/v1/common/article_list", {}, function(res) {
            if (res.state == 1) {
                that.setData({
                    article: res.datas
                })
            } else {
                utils.message(res.datas)
            }
        })
    },
	//文章详情
	articledetilTap:function(e){
		console.log();
		wx.navigateTo({
			url: "../articledetil/articledetil?id=" + e.currentTarget.dataset.id,
			success: function(res) {},
			fail: function(res) {},
			complete: function(res) {},
		})
	},
	onreturnCloseTap:function(e){
		this.setData({
			isreturn: false
		})
	},
	//轮播图跳转
	onSliderTap:function(e){
		if (e.currentTarget.dataset.type===0){
				wx.navigateTo({
					url: '../storeShop/storeShop?id=' + e.currentTarget.dataset.storeid,
				})
		}
		if (e.currentTarget.dataset.type == 1) {
			wx.navigateTo({
				url: '../storeshopdetils/storeshopdetils?slider_id=' + e.currentTarget.dataset.id,
			})
		}
		if (e.currentTarget.dataset.type == 2){

			this.setData({
				image: e.currentTarget.dataset.image,
				isreturn: true
			})
		}
	},
    //店铺列表
    storeList: function () {
        var that = this;
        console.log(that.data.schoolid)
        utils.http("/api/v1/store/store_list", {
            latitude: wx.getStorageSync("localhost").latitude, 
            longitude: wx.getStorageSync("localhost").longitude, 
            school_id: wx.getStorageSync("schoolInfo").schoolid
        }, function (res) {
            if (res.state == 1) {
                that.setData({
                    store: res.datas
                })
            } else {
                utils.message(res.datas)
            }
        })
    },
	//学校列表
	schoolList: function () {
		var that = this;
		utils.http("/api/v1/common/school_list", {
			keyword: that.data.keyword,
			page: that.data.curPage
		}, function (res) {
			if (res.state == 1) {
				var allpost = that.data.school;
				if (allpost == undefined) {
					allpost = [];
				}
				for (var i in res.datas) {
					allpost.push(res.datas[i])
				}
				if (res.datas.length < 10) {
					that.setData({
						tishi_title: '已加载全部',
					});
				} else {
					that.setData({
						tishi_title: '加载更多',
					});
				}
				that.setData({
					school: allpost,
					ready1: res.datas.length == 0 ? 1 : 2,
				})
			} else {
				utils.message(res.datas)
			}
		})
	},
    //热销排行榜
    goodsList: function (currentPage) {
        var that = this;
        utils.http("/api/v1/goods/goods_list",{
			page: currentPage, 
			school_id: wx.getStorageSync("schoolInfo").schoolid
        }, function (res) {
            if (res.state == 1) {
                var allpost = that.data.goods;
                if (allpost == undefined) {
                    allpost = [];
                }
                for (var i in res.datas) {
                    allpost.push(res.datas[i])
                }
                if (res.datas.length < 10) {
                    that.setData({
                        tishi_title: '已加载全部',
                    });
                } else {
                    that.setData({
                        tishi_title: '加载更多',
                    });
                }
               that.setData({
                   goods: allpost,
                   ready: res.datas.length == 0 ? 1 : 2,
               })
            } else {
                utils.message(res.datas)
            }
        })
    },
    //进入店铺
    onStoreShopTap: function(e) {
        wx.navigateTo({
            url: '../storeShop/storeShop?id=' + e.currentTarget.dataset.storeid
        })
    },
    
    //进入搜索页面
    onSearchTap: function() {
        wx.navigateTo({
            url: '../search/search'
        })
    },
    //查看更多店铺
    allStoreList: function() {
        wx.navigateTo({
            url: '../allStoreShop/allStoreShop'
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this.setData({
            goods: []
        })
        this.getUserLocation();
        this.systemInfo();
        this.sliderList();
        this.articleList();
        this.goodsList(1);
        this.schoolList(this.data.keyword);
        wx.stopPullDownRefresh();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        var that = this;
        if (that.data.ready == 2) {
            var page = that.data.currentPage + 1
            that.setData({
                currentPage: page,
            })
            that.goodsList(page);
        }

    },

	bindscrolltolowerTap:function(){
		var that = this;
		console.log("ksdjflk")
		if (that.data.ready1 == 2) {
			var page = that.data.curPage + 1
			that.setData({
				curPage: page,
			})
			that.schoolList();
		}
	},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})